package org.example.dataStorage.Map;

import com.alibaba.fastjson2.JSON;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

public class DataStorageService {

    private final DataStorageConfig config;
    private final Properties prop = new Properties();


    public DataStorageService(DataStorageConfig config) {
        this.config = config;
        // 确保存储目录存在
        ensureStorageDirectory();
    }

    //读取
    public HashMap<Object, Object> getAllData() {
        try (FileInputStream input = new FileInputStream(config.getStoragePath() + config.getFILE_NAME())) {
            // 加载属性文件（自动处理UTF-8编码）
            prop.load(input);
        } catch (IOException ex) {
            System.err.println("读取配置失败: " + ex.getMessage());
        }
        return new HashMap<>(prop);
    }

    public void setData(Map<String, String> Data) {
        //保存到文件
        Data.forEach(prop::setProperty);

        //写入数据
        try (OutputStream output = new FileOutputStream(config.getStoragePath() + config.getFILE_NAME())) {
            prop.store(output, "Application Configuration");
            System.out.println("配置已成功保存");
        } catch (IOException ex) {
            System.err.println("保存配置失败: " + ex.getMessage());
        }
    }

    /**
     * 确保存储目录存在
     * 如果不存在就创建空配置文件
     * 注意：仅创建文件，不初始化内容
     */
    private void ensureStorageDirectory() {
        Path PropertiesReader = Path.of(new File(config.getStoragePath()).getAbsolutePath());
        Path PropertiesName = Path.of(new File(config.getStoragePath() + config.getFILE_NAME()).getAbsolutePath());

        try {
            if (!Files.exists(PropertiesReader)) {
                Files.createDirectories(PropertiesReader);
            }
            if (!Files.exists(PropertiesName)) {
                Files.createFile(PropertiesName);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }
}